<?php

namespace Users\Model;

use Zend\Db\TableGateway\TableGateway;

//use Zend\Db\Sql\Select;

class UploadImageTable {
	
	protected $tableGateway;
	
	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
		
	}
	
	public function saveUpload(UploadImage $upload)
	{
		$data = array(
				'filename' => $upload->filename,
				'label' => $upload->label,
				'user_id' => $upload->user_id,
				'thumbnail' => $upload->thumbnail,
					
		);
		$id = (int)$upload->id;
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($id));
		if ($id == 0) {
			$this->tableGateway->insert($data);
		} else {
			if ($this->getUpload($id)) {
				$this->tableGateway->update($data, array('id' => $id));
			} else {
				throw new \Exception('User ID does not exist');
			}
		}
	}
	
	public function getUpload($id)
	{
		$id = (int) $id;
		$rowset = $this->tableGateway->select(array('id' => $id));
		$row = $rowset->current();
		if (!$row) {
			throw new \Exception("Could not find row $id");
		}
		return $row;
	}
	
	public function getUploadsByUserId($userId)
	{
		$userId = (int) $userId;
		$rowset = $this->tableGateway->select(
				array('user_id' => $userId));
		return $rowset;
	}
	
	public function getUploadfilename($filename)
	{
		$name = (string)$filename;
		//throw new \Exception("Could not find row $name");
		$rowset = $this->tableGateway->select(array('filename' => $name));
		$row = $rowset->current();
		//throw new \Exception("Could not find row $rowset");
		if (!$row) {
			//throw new \Exception("Could not find row $row");
			return NULL;
		}
		return $row;
	}
	
	public function getlastUpload()
	{
		//$rowset = array();
		$rowset = $this->tableGateway->getLastInsertValue();
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('  '.var_dump($rowset));
		return $rowset;
	}
	
	public function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		return $resultSet;
	}
	
	public function deleteUpload($id)
	{
		$this->tableGateway->delete(array('id' => $id));
	}
	
	
	
}

?>